package client.GUI.dashboard;

import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
import javax.swing.JPanel;

import server.conn.ConnectionThread;

import client.GUI.GUIConstants;
import client.backend.Connection;
import client.backend.price.Price;
import client.backend.price.PriceController;


/**
 * Creates a table that displays the price history of a currency pair
 *
 */
public class PriceHistoryPanel extends JFrame{
	JTable table;
	String [] colNames = new String[2];
	String curr1, curr2;
	int limit = 50;  //  @jve:decl-index=0:
	int bS;
	
	/**
	 * Creates the price history table based on the two currencies
	 * involved and whether the currency pair is being bought
	 * or sold by the user
	 * 
	 * @param currPair - A String containing curr1 + " - " + curr2
	 * @param buySell  - An int specifying whether the user 
	 * 					 is buying or selling the currency pair
	 * @throws IOException
	 */
	public PriceHistoryPanel(String currPair, int buySell) throws IOException{
		setCurrencies(currPair);
		
		if(buySell == 1){
			bS = 1;
		}
		else{
			bS = 2;
		}
		
		table = new JTable(new DefaultTableModel(getInfo(), GUIConstants.PriceHistoryColumnNames)){
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int col){
				return false;
			}
		};
	
		JScrollPane scrollPane = new JScrollPane(table);
        this.add(scrollPane, BorderLayout.CENTER);
	}
	
	/**
	 * Separates the currPair string into curr1 and curr2
	 * 
	 * @param currPair - A String containing the currency pair
	 */
	public void setCurrencies (String currPair){
		curr1 = currPair.substring(0, 3);
		curr2 = currPair.substring(3);
	}
	
	/**
	 * Creates a 2 dimensional array that contains the
	 * price fluctuations for the two currencies
	 * 
	 * @return info - A 2 dimensional string array containing the row data for the table
	 * @throws IOException
	 */
	public String[][] getInfo() throws IOException{
		LinkedList<Price> prices = PriceController.getInstance().getPrice(curr1, curr2).getHistory(limit, bS);
		String [][] info = new String[prices.size()][3];
		int i = 0;
		Long time;
		SimpleDateFormat d = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
		Float ratio;
		
		for(Price price : prices){
			time = price.getTime();
			ratio = price.getBuy();
			
			info[i][0] = d.format(new Date(time*1000));
			info[i][1] = ratio.toString();
			i++;
		}
		return info;
	}
}
